﻿using MN.Framework.Security;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MN.Framework.Common.Security
{
    public class SqlMembership : IMembership
    {
        SecurityContext SecContext { get; set; }
        IUser CurrentUser;
        public virtual string EncryptKey { get { return "xpmntz777pmjmsb"; } }

        public SqlMembership()
        {
            SecContext = new SecurityContext(BaseContext.GetConnectionString());
        }
        public IUser getUser(string Username)
        {
            Username = Username.ToLower();
            var user = SecContext.Users.SingleOrDefault(u => u.Username.ToLower() == Username);
            return user;
        }
        public bool validateUser(string Username, string Password)
        {
            Username = Username.ToLower();
            var user = getUser(Username);
            if (user != null)
            {
                if (user.Password.Equals(Password, StringComparison.InvariantCultureIgnoreCase))
                {
                    CurrentUser = user;
                    return true;
                }
            }
            return false;
        }
        public string generatePassword(string password)
        {
            switch (PasswordEncryptType)
            {
                case PasswordType.Normal:
                    return password.ToLower();
                case PasswordType.MD5:
                    return CryptoService.Encrypt(password, EncryptKey);
                default:
                    return password;
            }
        }
        public IUser[] getUsersByRole(string RoleName)
        {
            throw new NotImplementedException();
        }

        public IUser[] getUsersByRole(IRole Role)
        {
            throw new NotImplementedException();
        }

        public IRole getRole(string RoleName)
        {
            throw new NotImplementedException();
        }

        public IRole[] getUserRoles(string UserName)
        {
            throw new NotImplementedException();
        }

        public IRole[] getUserRoles(IUser User)
        {
            throw new NotImplementedException();
        }

        public IUser createUser(string UserName, string Password)
        {
            throw new NotImplementedException();
        }

        public IUser createUser(string UserName, string Password, IRole Role)
        {
            throw new NotImplementedException();
        }

        public bool deleteUser(string UserName)
        {
            throw new NotImplementedException();
        }

        public PasswordType PasswordEncryptType
        {
            get { return PasswordType.Normal; }
        }        

        public IUser getCurrentUser()
        {
            return CurrentUser;
        }
    }
}
